package com.friends.utils.validate.global;

import com.friends.utils.validate.exception.MyRunTimeException;
import com.friends.utils.validate.util.EnvDetector;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;

/**
 * 统一异常处理类
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private EnvDetector envDetector;


    @ExceptionHandler({IllegalStateException.class, IllegalArgumentException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class, MyRunTimeException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object NgsExceptionError(Exception e) {
        if (envDetector.isDev() || envDetector.isTest()) {
            String stackTrace = ExceptionUtils.getStackTrace(e);
            log.error("系统服务异常:{}", stackTrace);
            HashMap<String, String> resultMap = Maps.newHashMap();
            resultMap.put("code", "500");
            resultMap.put("message", e.getMessage());
            resultMap.put("stackTrace", stackTrace);
            return resultMap;
        } else {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("内部服务异常");
        }
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object error(Exception e) {
        if (envDetector.isDev() || envDetector.isTest()) {
            String stackTrace = ExceptionUtils.getStackTrace(e);
            log.error("系统服务异常:{}", stackTrace);
            HashMap<String, String> resultMap = Maps.newHashMap();
            resultMap.put("code", "500");
            resultMap.put("message", "内部服务异常");
            resultMap.put("stackTrace", stackTrace);
            return resultMap;
        } else {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("内部服务异常");
        }
    }
}